package dryven.config.xml.jdbctags;

import org.xml.sax.Attributes;

import dryven.config.xml.AbstractJdbcConfigurationElement;
import dryven.config.xml.MemoryApplicationConfiguration;
import dryven.config.xml.MemoryDatabaseConfiguration;

public class MySqlConfigurationElement extends AbstractJdbcConfigurationElement {

	@Override
	public MemoryDatabaseConfiguration readConnection(Attributes elementAttributes) {
		String server = elementAttributes.getValue("", "server");
		String user = elementAttributes.getValue("", "user");
		String pass = elementAttributes.getValue("", "pass");
		String portStr = elementAttributes.getValue("", "port");
		String schema = elementAttributes.getValue("", "schema");
		
		String url = createJDBCUrl(server, portStr, schema);
		
		MemoryDatabaseConfiguration cfg = new MemoryDatabaseConfiguration();
		cfg.setJDBCUrl(url);
		cfg.setDriverClass(getDriverClass());
		cfg.setPassword(pass);
		cfg.setUsername(user);
		return cfg;
	}

	private String createJDBCUrl(String server, String portStr,
			String schema) {
		Integer port = null;
		if(portStr!=null) {
			port = Integer.parseInt(portStr);
		}
		StringBuilder buf = new StringBuilder("jdbc:mysql://");
		buf.append(server);
		if(port!=null) {
			buf.append(":");
			buf.append(port);
		}
		buf.append("/");
		buf.append(schema);
		return buf.toString();
	}
	
	private String getDriverClass() {
		return "com.mysql.jdbc.Driver";
	}
}
